//
// Created by 张兮兮 on 2025/3/13.
//

#include "OpenWidget.h"
#include <QDebug>
#include <QDir>

OpenWidget::OpenWidget(QWidget *parent) : QWidget(parent) {
    socket = new QLocalSocket(this);
    connect(socket, &QLocalSocket::readyRead, this, &OpenWidget::readData);
    pid_t pid = 23043;
    QString processId = "socketHandPro" + QString::number(pid);
    qDebug() << "当前进程id" << processId;
    socketPath = QDir::temp().absoluteFilePath(processId);
    qDebug() << "System Info:" << QSysInfo::prettyProductName();
    process = new QProcess(this);
    // 设置进程 B 的可执行文件路径
    QString program = "/Users/zhanghongwei/Desktop/socket-temp/socket-project/build/Debug/socketPro";
    // 设置参数
    QStringList arguments;
//        pid_t pid = getpid(); // 获取当前进程的进程ID
//        arguments << processId << QString::number(pid);
    arguments << processId;
    arguments << "/Users/zhanghongwei/Desktop/socket-temp/socket-project/res/track";
    // 启动进程 B 并传递参数
    process->start(program, arguments);
    // 等待进程 B 启动完成
    if (!process->waitForStarted()) {
        qDebug() << "Failed to start process B";
    }
    connect(process, &QProcess::readyReadStandardError, this, &OpenWidget::handleProcessOutput);
    connect(process, &QProcess::readyReadStandardOutput, this, &OpenWidget::handleProcessOutput);

}


void OpenWidget::handleProcessOutput() {
    QByteArray outputError = process->readAllStandardError();
    QByteArray output = process->readAllStandardOutput();
    if (!outputError.isEmpty()) {
        qDebug() << "222222output:" << outputError;
    }
    if (!output.isEmpty()) {
        qDebug() << "1111111output:" << output;
    }
    if (outputError.contains("Server started successfully") || output.contains("Server started successfully")) {
        // 服务器已经启动，尝试连接
        socket->connectToServer(socketPath);
        if (socket->waitForConnected(3000)) {
            qDebug() << "Connected to server.";
        } else {
            qDebug() << "Unable to connect to server:" << socket->errorString();
        }
    }
    qDebug()<<"来爱仕达奋斗啥方式了";
}

void OpenWidget::readData() {
    qDebug()<<"readData";
}

OpenWidget::~OpenWidget() {
    qDebug()<<"析构";
    if (process && process->state() == QProcess::Running) {
        process->terminate();
        if (!process->waitForFinished(3000)) {
            qDebug()<<"强杀";
            process->kill(); // 强制杀死进程
        }
    }
}